import pymysql
import os


class MySQLDB:
    db_conn = None
    db_cursor = None
    db_where = []
    db_fields = []

    def __init__(self):
        # self.db_conn = pymysql.connect( host=os.getenv('DB_HOST', '127.0.0.1'), user=os.getenv('DB_USER', 'root'),  password=os.getenv('DB_PASSWORD', '123123'), database=os.getenv('DB_NAME', 'test'), port=int(os.getenv('DB_PORT', 3306)) )
        pass

    def __del__(self):
        if self.db_conn != None:
            self.db_conn.close()
            self.db_conn = None

    def connect(self, options: dict):
        self.db_conn = pymysql.connect(host=options['host'], user=options['user'], password=options['pwd'],
                                       database=options['db'], port=options['port']);

    def close(self):
        if self.db_conn != None:
            self.db_conn.close()
            self.db_conn = None
        # print("close db")

    def getAll(self, sql):
        if self.db_conn != None:
            cursor = self.db_conn.cursor(cursor=pymysql.cursors.DictCursor)
            cursor.execute(sql)
            return cursor.fetchall()
        return []

    def getOne(self, sql):
        if self.db_conn != None:
            cursor = self.db_conn.cursor(cursor=pymysql.cursors.DictCursor)
            cursor.execute(sql)
            return cursor.fetchone()
        return []

    def query(self, sql):
        if self.db_conn != None:
            cursor = self.db_conn.cursor()
            r = cursor.execute(sql)
            self.db_conn.commit()
            return r
        return False
